from django import forms
from django.core.exceptions import ValidationError
from user.models import VSession,User
from notice.models import NoticeInfo
import pdb


def token_check(value):
    # 验证token必须存在
    sessionList = VSession.objects.filter(token=value)
    if not sessionList.exists():
        errMsg = 'token Error'
        isValidOk = False
        raise ValidationError(errMsg)
    else:
        session = sessionList[0]



def noticeId_check(value):
    # 验证软件id必须存在
    if value != -1:
        is_num_by_except(value)
        notice = NoticeInfo.objects.filter(pk=value)
        if not notice.exists():
            errMsg = 'noticeId Error'
            raise ValidationError(errMsg)


def maxItem_check(value):
    if value < 1:
        errMsg = 'maxItem Error'
        raise ValidationError(errMsg)


def page_check(value):
    if value < 1:
        errMsg = 'page Error'
        raise ValidationError(errMsg)

def is_num_by_except(num):
    try:
        int(num)
        return True
    except ValueError:
        errMsg = 'value not int'
        raise ValidationError(errMsg)


class AddNoticeForm(forms.Form):
    noticeContent = forms.CharField(max_length=16000)
    noticeTitle = forms.CharField(max_length=100)
    token = forms.CharField(max_length=100,validators=[token_check])
    isView = forms.CharField(max_length=200, required=False)

class GetNoticeForm(forms.Form):
    token = forms.CharField(max_length=100,validators=[token_check])
    maxItem = forms.IntegerField(validators=[maxItem_check])
    page = forms.IntegerField(validators=[page_check])
    noticeState = forms.CharField(max_length=200, required=False)

class NoticeContentForm(forms.Form):
    token = forms.CharField(max_length=100,validators=[token_check])
    noticeId = forms.IntegerField(validators=[noticeId_check]) 

class OptionNoticeForm(forms.Form):
    token = forms.CharField(max_length=100,validators=[token_check])
    noticeId = forms.IntegerField(validators=[noticeId_check]) 
    option = forms.CharField(max_length=20)